package com.jy.framework.config.json;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;
//@JsonDeserialize(using = DeserializerBigDecimal.class)
//@JsonSerialize(using = SerializerBigDecimal.class)
//private BigDecimal warePrice;
/**
 * 出参保留两位小数
 */
public class DeserializerBigDecimal extends JsonDeserializer<BigDecimal> {

    /**
     * 出参保留两位小数
     * @param jsonParser
     * @param deserializationContext
     * @return
     * @throws IOException
     */
    @Override
    public BigDecimal deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        try {
            if (Objects.isNull(jsonParser.getDecimalValue())) {
                return null;
            } else {
                // 这里取floor
                BigDecimal bigDecimal = jsonParser.getDecimalValue().setScale(2, RoundingMode.FLOOR);
                return bigDecimal;
            }
        } catch (IOException e) {
//            兼容字符串类型
            // 这里取floor
            String valueAsString = jsonParser.getValueAsString();
            if (StrUtil.isBlank(jsonParser.getValueAsString())){
                return null;
            }
            BigDecimal bigDecimal = new BigDecimal(valueAsString).setScale(2, RoundingMode.FLOOR);
            return bigDecimal;
        }
    }

}
